package com.jingxing.service.impl;

import com.jingxing.service.CodeService;
import com.jingxing.utils.TotalUtil;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class CodeServiceImpl implements CodeService {
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 获取验证码
     * @param phone
     * @return
     */
    @Override
    public boolean getCode(String phone) {
        boolean flag =false;
        String code = "";
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            int r = random.nextInt(10); //每次随机出一个数字（0-9）
            code = code + r;  //把每次随机出的数字拼在一起
        }
        SendSmsResponse res = null;
        try {
            res = TotalUtil.getSendSmsResponse(phone, code,"985025",null);
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
        }
        // 可以取出单个值，您可以通过官网接口文档或跳转到 response 对象的定义处查看返回字段的定义
        if(res.getRequestId()!=null){
            redisTemplate.boundValueOps(phone).set(code,1, TimeUnit.MINUTES);
            flag=true;
        }
        return flag;
    }
}
